/**
 * @file mainTask.c
 * @brief 系统主任务实现（基于FreeRTOS + CMSIS-OS v2）
 */

#include "mainTask.h"
#include <stdio.h>
#include <string.h>

// 全局设备状态变量定义
DeviceStatus deviceStatus = {0};
osThreadId_t mainTaskId = NULL;

// 硬件接口函数声明(伪代码)
void hardwareInit(void);
bool isCardSwiped(void);
bool isQRCodeScanned(void);
void sendCardData(void);
void sendQRCodeData(void);
void sendResponseWithUserData(uint32_t userId, float balance);
bool isStartKeyPressed(void);
bool isEndKeyPressed(void);
void openWaterValve(void);
void closeWaterValve(void);
void turnOnUvLamp(void);
void turnOffUvLamp(void);
void clearPulseCounter(void);
uint32_t readPulseCounter(void);
float calculateWaterAmount(uint32_t pulses);
float calculateCost(float waterAmount);
float readUvIntensity(void);
float readUvLampTemperature(void);
float readEnvironmentTemperature(void);
void adjustUvLampOutput(bool highPower);
void displayWaterVolume(float volume);
void displayBalance(float balance);
void displayUvIntensity(float intensity);
bool isValveClosed(void);
void openDrainValve(void);
void closeDrainValve(void);
bool isWaterLeakDetected(void);
bool isVibrationDetected(void);
bool isDoorOpened(void);
void sendAlarmMessage(const char* alarmType);
void turnOffUvLampPower(void);
void ledBlink(bool enable);
void buzzerBeep(bool enable);

/**
 * @brief 系统初始化函数
 */
void initializeSystem(void) {
    memset(&deviceStatus, 0, sizeof(DeviceStatus));
    deviceStatus.systemState = SYSTEM_STATE_INIT;
    deviceStatus.drainValveState = DRAIN_VALVE_CLOSED;
}

/**
 * @brief 创建主任务
 * @return 任务ID
 */
osThreadId_t createMainTask(void) {
    const osThreadAttr_t mainTaskAttributes = {
        .name = "MainTask",
        .priority = MAIN_TASK_PRIORITY,
        .stack_size = MAIN_TASK_STACK_SIZE
    };
    
    mainTaskId = osThreadNew(mainTask, NULL, &mainTaskAttributes);
    return mainTaskId;
}

/**
 * @brief 系统主任务
 * @param argument 任务参数（未使用）
 */
void mainTask(void *argument) {
    // 初始化设备状态
    if (deviceStatus.systemState == SYSTEM_STATE_INIT) {
        hardwareInit();
        deviceStatus.systemState = SYSTEM_STATE_WAIT_USER_DATA;
    }
    
    for (;;) {
        // 系统状态机
        switch (deviceStatus.systemState) {
            case SYSTEM_STATE_WAIT_USER_DATA: {
                // 状态1: 初始状态(等待用户数据)
                if (isCardSwiped()) {
                    // 刷卡——>发送刷卡数据——>返回应答（用户数据：用户id和用户余额）
                    sendCardData();
                    // 假设这里获取了用户数据
                    deviceStatus.userId = 12345;
                    deviceStatus.userBalance = 100.0;
                    deviceStatus.currentBalance = deviceStatus.userBalance;
                    sendResponseWithUserData(deviceStatus.userId, deviceStatus.userBalance);
                    deviceStatus.systemState = SYSTEM_STATE_WAIT_START_KEY;
                } else if (isQRCodeScanned()) {
                    // 用户手机刷二维码——>返回应答（用户数据：用户id和用户余额）
                    sendQRCodeData();
                    // 假设这里获取了用户数据
                    deviceStatus.userId = 67890;
                    deviceStatus.userBalance = 50.0;
                    deviceStatus.currentBalance = deviceStatus.userBalance;
                    sendResponseWithUserData(deviceStatus.userId, deviceStatus.userBalance);
                    deviceStatus.systemState = SYSTEM_STATE_WAIT_START_KEY;
                }
                break;
            }
            
            case SYSTEM_STATE_WAIT_START_KEY: {
                // 状态2: 等待按下开始按键
                // 累计超时时间
                deviceStatus.timeoutCounter++;
                
                if (isStartKeyPressed() && deviceStatus.timeoutCounter <= TIMEOUT_LIMIT) {
                    // 转换条件1：在超时时间内，按下开始按键
                    // 1）打开取水阀，取水阀开关状态为开
                    openWaterValve();
                    deviceStatus.waterValveState = true;
                    
                    // 2）打开紫外灯
                    turnOnUvLamp();
                    deviceStatus.uvLampState = true;
                    
                    // 3）清除累计流量值
                    clearPulseCounter();
                    deviceStatus.pulseCounter = 0;
                    deviceStatus.totalWaterVolume = 0;
                    
                    // 4）转换到状态3
                    deviceStatus.systemState = SYSTEM_STATE_WATER_DISPENSING;
                    deviceStatus.dispenseTimeCounter = 0;
                } else if (deviceStatus.timeoutCounter > TIMEOUT_LIMIT) {
                    // 转换条件2：大于超时时间，未按下按键，发送用户结束取水事件（取水量0）
                    // 发送用户结束取水事件逻辑
                    deviceStatus.systemState = SYSTEM_STATE_END_DISPENSE;
                    deviceStatus.displayTimeCounter = 0;
                }
                break;
            }
            
            case SYSTEM_STATE_WATER_DISPENSING: {
                // 状态3: 开始取水
                // 脉冲计数
                deviceStatus.pulseCounter = readPulseCounter();
                
                // 定时执行以下操作
                // 1）读取流量脉冲数，计算累计用水金额，计算余额
                float waterAmount = calculateWaterAmount(deviceStatus.pulseCounter);
                deviceStatus.totalWaterVolume = waterAmount;
                float cost = calculateCost(waterAmount);
                deviceStatus.currentBalance = deviceStatus.userBalance - cost;
                
                // 2）读取紫外强度，显示
                deviceStatus.uvIntensity = readUvIntensity();
                displayUvIntensity(deviceStatus.uvIntensity);
                displayBalance(deviceStatus.currentBalance);
                
                // 3）紫外累计工作时长，保存并推送
                deviceStatus.uvWorkTimeCounter++;
                
                // 4）读取紫外灯温度，温度超过高温限制值，紫外灯低档输出；温度低于低温限制值，紫外灯高档输出
                deviceStatus.uvLampTemperature = readUvLampTemperature();
                if (deviceStatus.uvLampTemperature > UV_HIGH_TEMP_THRESHOLD) {
                    adjustUvLampOutput(false); // 低档输出
                } else if (deviceStatus.uvLampTemperature < UV_LOW_TEMP_THRESHOLD) {
                    adjustUvLampOutput(true);  // 高档输出
                }
                
                // 转换条件1：按下结束按键，开始关闭阀门
                if (isEndKeyPressed()) {
                    deviceStatus.systemState = SYSTEM_STATE_CLOSE_VALVE;
                }
                // 转换条件2：用户余额不足，开始关闭阀门
                else if (deviceStatus.currentBalance <= 0) {
                    deviceStatus.systemState = SYSTEM_STATE_CLOSE_VALVE;
                }
                break;
            }
            
            case SYSTEM_STATE_CLOSE_VALVE: {
                // 状态4: 关阀
                // 关闭取水阀
                closeWaterValve();
                deviceStatus.waterValveState = false;
                
                // 关闭紫外灯
                turnOffUvLamp();
                deviceStatus.uvLampState = false;
                
                // 检测环境温度
                float envTemperature = readEnvironmentTemperature();
                
                // 检测到阀门关到位
                if (isValveClosed()) {
                    // 1）计算本次总取水量，并显示在屏幕中
                    displayWaterVolume(deviceStatus.totalWaterVolume);
                    
                    // 3）如果温度小于设置阈值，打开泄水阀，泄水阀开关状态为开
                    if (envTemperature < ENV_TEMP_THRESHOLD) {
                        openDrainValve();
                        deviceStatus.drainValveState = DRAIN_VALVE_OPEN;
                        deviceStatus.drainValveOpenTimer = 0;
                    }
                    
                    // 4）转换到状态5
                    deviceStatus.systemState = SYSTEM_STATE_END_DISPENSE;
                    deviceStatus.displayTimeCounter = 0;
                }
                break;
            }
            
            case SYSTEM_STATE_END_DISPENSE: {
                // 状态5: 结束取水，取水消息回显
                // 累计时间
                deviceStatus.displayTimeCounter++;
                
                // 转换条件：如果累计时间大于设定回显时间，转换到状态0
                if (deviceStatus.displayTimeCounter > DISPLAY_TIME_LIMIT) {
                    deviceStatus.systemState = SYSTEM_STATE_WAIT_USER_DATA;
                    deviceStatus.timeoutCounter = 0;
                }
                break;
            }
            
            default:
                // 错误状态，回到初始状态
                deviceStatus.systemState = SYSTEM_STATE_WAIT_USER_DATA;
                break;
        }
        
        // 与状态机并行执行：泄水阀控制
        if (deviceStatus.drainValveState == DRAIN_VALVE_OPEN) {
            // 3.1 如果泄水阀状态为打开，累计泄水阀打开后累计时间，时间大于设定阈值，泄水阀状态改为关闭中
            deviceStatus.drainValveOpenTimer++;
            if (deviceStatus.drainValveOpenTimer > DRAIN_VALVE_OPEN_TIME_LIMIT) {
                deviceStatus.drainValveState = DRAIN_VALVE_CLOSING;
                deviceStatus.drainValveClosingTimer = 0;
            }
        } else if (deviceStatus.drainValveState == DRAIN_VALVE_CLOSING) {
            // 3.2 如果泄水阀为正在关闭状态，累计泄水阀关闭累计计时，时间大于设定阈值，泄水阀状态为关闭
            deviceStatus.drainValveClosingTimer++;
            if (deviceStatus.drainValveClosingTimer > DRAIN_VALVE_CLOSING_TIME_LIMIT) {
                deviceStatus.drainValveState = DRAIN_VALVE_CLOSED;
                closeDrainValve();
            }
        }
        
        // 与状态机并行执行：浸水检测
        if (isWaterLeakDetected()) {
            // 检测到浸水，发送报警消息，关闭紫外灯，紫外灯关闭电源
            sendAlarmMessage("WATER_LEAK");
            turnOffUvLamp();
            deviceStatus.uvLampState = false;
            turnOffUvLampPower();
        }
        
        // 与状态机并行执行：振动倾倒检测
        if (isVibrationDetected()) {
            // 检测到倾倒，发送报警消息
            sendAlarmMessage("VIBRATION");
        }
        
        // 与状态机并行执行：意外开门检测
        if (isDoorOpened()) {
            // 检测到开门了，发送报警消息
            sendAlarmMessage("DOOR_OPENED");
        }
        
        // 任务调度延迟，10ms执行一次主循环
        osDelay(10);
    }
}